import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {PageContainer, ProTable} from '@ant-design/pro-components';
import {Button, message, Modal} from 'antd';
import {useRef} from 'react';
import {useLocation, useParams} from 'react-router-dom';
import services from '@/services/nginx';

const {records,deleteRecord} = services.DomainParsingRecordController;


/**
 * 删除记录
 * @param domain 域名
 */
const handleRemove = async (params: API.DeleteRecord) => {
    const hide = message.loading('正在删除,请稍后...', 0);
    try {
        // console.log("删除记录：", params)
        const resp =  await deleteRecord(params);
        hide();
        message.success(resp.message);
        return true;
    } catch (error) {
        hide();
        return false;
    }
  };


const TableList: React.FC<unknown> = () => {
    const actionRef = useRef<ActionType>();

    // 地址栏参数
    const { domain } = useParams();
    // 确保accessId不是undefined

    const location = useLocation();
    const inputParams = location.state as {
        recordCount: number,
        accessId: string;
        domain: string;
        domainId: string;
        cloud: string;
    };



const columns: ProColumns<API.DnsDomainRecord>[] = [
    {
       title: '记录ID',
       key: 'recordId',
       dataIndex: 'recordId',
       valueType: 'text',
       sorter: true,
       hideInSearch: true,
       hideInForm: true,
       hideInTable: true,
       search: false
      },
     {
       title: '主机记录',
       dataIndex: 'rr',
       tooltip: '一般指域名前缀[华为云不一样]',
       copyable: true,
       ellipsis: true,
       search: false,
       formItemProps: {
         rules: [
           {
             required: true,
             message: '主机记录为必填项',
           },
         ],
       },
     },
     {
       title: '主域名',
       dataIndex: 'domain',
       valueType: 'text',
       copyable: true, // 启用可复制功能
       ellipsis: true, // 启用文本省略
       search: false,
       formItemProps: {
         rules: [
           {
             required: true,
             message: '主域名为必填项',
           },
         ],
       },
     },
     {
       title: '记录类型',
       dataIndex: 'type',
       valueType: 'text',
       tooltip: '指解析记录的用途',
       search: false,
       formItemProps: {
         rules: [
           {
             required: true,
             message: '主域名为必填项',
           },
         ],
       },
     },
     {
       title: '记录值',
       dataIndex: 'value',
       valueType: 'text',
       copyable: true, // 启用可复制功能
       ellipsis: true, // 启用文本省略
       tooltip: '一般是填写服务器的IP地址',
       search: false,
     },
     {
       title: 'ttl/s',
       dataIndex: 'ttl',
       valueType: 'text',
       tooltip: '指解析结果在Local DNS中的缓存时间',
       search: false,
     },
     {
       title: '解析请求来源(ISP)',
       dataIndex: 'line',
       valueType: 'text',
       tooltip: '指域名访问者所在的地区和使用的运营商网络',
       search: false,
     },
     {
       disable: true,
       title: '状态',
       tooltip: '解析记录在云解析DNS中的启用情况',
       dataIndex: 'status',
       filters: true,
       onFilter: true,
       ellipsis: true,
       valueType: 'select',
       search: false,
       valueEnum: {
         DISABLE: {
           text: '关闭',
           status: 'DISABLE',
         },
         ENABLE: {
           text: '正常',
           status: 'ENABLE',
         }
         ,
         ACTIVE: {
           text: '正常',
           status: 'ACTIVE',
         }
       },
     },
     {
       title: '备注',
       dataIndex: 'remark',
       valueType: 'text',
       search: false,
     },
     {
       title: '操作',
       valueType: 'option',
       key: 'option',
       render: (text, record, _, action) => [
         <a
           key="editable"
           onClick={() => {
               Modal.confirm({
                   title: '确认删除',
                   content: `确定要删除 ${record.rr} 吗？`,
                   okText: '确认',
                   okType: 'danger',
                   cancelText: '取消',
                   onOk: async () => {
                     const success = await handleRemove({
                        accessId: inputParams.accessId,
                        recordId: record.recordId,
                        cloud: inputParams.cloud,
                        zoneId: record.zoneId
                     });
                     if (success) {
                       actionRef.current?.reloadAndRest?.();
                     }
                   },
               });
            }}
         >
           删除
         </a>
       ],
     },
   ];

    return (
        <PageContainer
        header={{
            title: <span>
                        <span style={{ color: 'red'  }}>{domain}</span>域名解析记录
                    </span>,
        }}
      >
        <ProTable<API.DnsDomainRecord>
            columns={columns}
            actionRef={actionRef}
            search={false}
            cardBordered
            request={async (params) => {
                const {data,success} = await records(inputParams.accessId,{
                    ...inputParams
                });
                return {
                data: data,
                //   total: data?.total,
                //   pageSize: data?.pageSize,
                //   current: data?.currentPage,
                success,
                };
            }}
            editable={{
            type: 'multiple',
            }}
            columnsState={{
            persistenceKey: 'pro-table-singe-demos',
            persistenceType: 'localStorage',
            defaultValue: {
                option: { fixed: 'right', disable: true },
            },
            onChange(value) {
                console.log('value: ', value);
            },
            }}
            rowKey="recordId"
            options={{
            setting: {
                listsHeight: 400,
            },
            }}
            pagination={{
            pageSize: 10,
            onChange: (page) => console.log(page),
            }}
            dateFormatter="string"
            toolBarRender={() => [
            <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                    message.warning("功能建设中.....")
                actionRef.current?.reload();
                }}
                type="primary"
            >
                添加记录
            </Button>,
            ]}
        />
    </PageContainer>
    );

}

export default TableList;
